package cn.xeblog.server.handler;

import cn.hutool.core.util.StrUtil;
import cn.xeblog.commons.entity.User;
import cn.xeblog.server.action.ChannelAction;
import cn.xeblog.server.builder.ResponseBuilder;
import cn.xeblog.server.cache.UserCache;
import cn.xeblog.server.config.ServerConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Map;

/**
 * @author eleven
 * @date 2024/11/1 15:08
 * @apiNote
 */
public class RandomAdminHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        randomAdminUserAndBroadcast();
        super.channelActive(ctx);
    }

    /**
     * 随机管理员，并且广播
     */
    public static void randomAdminUserAndBroadcast() {
        Map<String, User> userMap = UserCache.getUserMap();
        ServerConfig config = ServerConfig.getConfig();
        int limit = config == null ? 0 : config.getRandomAdminMinUserNum();
        if (userMap.size() > limit && UserCache.adminUser == null) {
            User user = UserCache.randomAdminUser();
            if (user != null) {
                String adminChangeStr = StrUtil.format("恭喜塘友 {} 被随机为本小时的管理员！！！ 无人扶我青云志，我自踏雪至山巅", user.getUsername());
                ChannelAction.send(ResponseBuilder.system(adminChangeStr));
            }
        }
    }
}
